package com.odianyun.hello.service.impl;

import com.odianyun.hello.mapper.UUserMapper;
import com.odianyun.hello.model.VO.UUser;
import com.odianyun.hello.service.IUUserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

@Service
public class UUserServiceImpl implements IUUserService {

    @Resource
    private UUserMapper uuserMapper;

    @Resource
    private RedisTemplate<Object,Object> redisTemplate;

    public static final String CACHE_USER_INFO_KEY_PREFIX="userinfo";

    @Override
    public void updateBatch(Long id,String password) {
        String key = CACHE_USER_INFO_KEY_PREFIX + id;
        redisTemplate.delete(key);
        uuserMapper.updateBatch(id,password);
    }

    @Override
    public List<UUser> findById(Long id) {
        ValueOperations operations = redisTemplate.opsForValue();//指定从redis缓存中获取数据
        String key = CACHE_USER_INFO_KEY_PREFIX + id;
        List<UUser> cacheUUser = (List<UUser>) operations.get(key);//获取缓存中的UUser数据
        if (null != cacheUUser) {//如果从缓存中拿的数据不为空，则直接返回
            System.out.println("使用了redis缓存");
            return  cacheUUser;
        }
        List<UUser> list = uuserMapper.findById(id);
        operations.set(key, list);
        return list;
    }
}
